local graphics = require("BBE.graphics")
local phisics = require("BBE.Phisics")

local ecs = {}

ecs.Component = {}
ecs.updates_function_list = {}

function ecs.root(pos, scale, rotate)
    return {pos, scale, rotate, objects = {}}
end

function ecs.object(name, root, pos, scale, rotate)

    local abs_pos = {pos[1]+root.pos[1], pos[2]+root.pos[2], pos[3]+root.pos[3]}
    local abs_scale = {scale[1]+root.scale[1], scale[2]+root.scale[2], scale[3]+root.scale[3]}
    local abs_rotate = {rotate[1]+root.rotate[1], rotate[2]+root.rotate[2], rotate[3]+rotate[3]}

    root.objects[name] = {
        abs_pos, abs_scale, abs_rotate, 
        objects = {}, 
        components = {}, 
        scripts = {}
    }

    return root.objects[name]
end

function ecs.delateObject(root, object)
    table.remove(root.objects, object)
end

--[[
    Component system
]]--

function ecs.addComponent(object, component_name)
    if not object.components then
        object.components = {}
    end
    object.components[component_name] = ecs.Component[component_name]
    object.components[component_name].start(object)
    table.insert(ecs.updates_function_list, {object.components[component_name].update, object})
end

function ecs.update(root)
    for i = 1, #ecs.updates_function_list do
        ecs.updates_function_list[i][1](root, ecs.updates_function_list[2])
    end
end

ecs.Component["RenderSprite"] = {
    sprite = nil,
    start = function(object)
        object.components["RenderSprite"].sprite = graphics.sprite.NewSprite(object.components["RenderSprite"])
    end,
    update = function(root, object)
    end,
    destroy = function (object)
        graphics.sprite.Delete(object.components["RenderSprite"].sprite)
    end
}

ecs.Component["RenderModel"] = {
    model = nil,
    start = function(object)
        object.components["RenderModel"].model = graphics.model.Create(object.components["RenderModel"], nil)
    end,
    update = function(root, object)
    end,
    destroy = function (object)
        graphics.sprite.Delete(object.components["RenderModel"].model)
    end
}

return ecs